import platform
import subprocess
import urllib.request

from mirrors.ustc import get_file_infos

os = platform.system().lower()
# 获取机器的硬件架构
machine = platform.machine().lower()
cpu = machine
print(f'os:{os}, cpu:{cpu}')
if machine in ['x86_64', 'amd64']:
    cpu = 'x86_64'
if machine in ['arm64', 'aarch64']:
    cpu = 'aarch64'
includes = ['.sh', '.exe', '.rpm', '.deb', '.pkg', '.bat', '.tar.gz', '.zip']
infos = get_file_infos('http://mirrors.zju.edu.cn/anaconda/miniconda/', includes)
target = None
for info in infos:
    name = info.file_name
    splits = name.split('.')[0].split('-')
    if 'latest' != splits[1]:
        continue
    if os != splits[2].lower():
        continue
    if splits[3] != cpu:
        continue
    if not target:
        target = info
        continue
    if splits[0] > target.file_name.split('.')[0].split('-')[0]:
        target = info
if not target:
    print('No target found')
    exit(1)
url = target.file_url
filename = target.file_name

# with urllib.request.urlopen(url) as response, open(filename, "wb") as file:
#     while True:
#         chunk = response.read(8192)
#         if not chunk:
#             break
#         file.write(chunk)
subprocess.run(['wget', '--no-check-certificate', url], check=True)
print("文件下载成功！")
subprocess.run(['chmod', '+x', filename], check=False)
subprocess.run([f'./{filename}'])
